<script setup>
  import { ref, onMounted, watch } from "vue";
  import { useStore } from "@/store/index.js";
  import { useStyleStore } from "@/store/styleStore.js";
  import searchApi from "@/api/search/index.js";
  import { ElMessage } from "element-plus";
  import ResponseUtil from "@/utils/ResponseUtil.js";
  import StringUtil from "@/utils/StringUtil.js";

  const store = useStore();
  const styleStore = useStyleStore();

  let temp = null;

  // 初始化样式
  onMounted(() => {
    temp = setTimeout(() => {
      initLoadVar.value = false;
    }, 1200);
  });

  // 监听搜索组件置顶显示状态，取消置顶时搜索文本框显示搜索两个字
  watch(styleStore.search, (oldVar, newVar) => {
    if (!newVar.top) {
      store.search.keyword = '搜索';
    }
  });

  let initLoadVar = ref(true);
  const inputFocus = ref(null)

  // 关键词联想词列表
  let suggestList = ref([]);
  let suggestHeight = ref(0);

  // 所有引擎列表
  let searchEngineList = ref([
    {
      id: 1,
      name: '百度搜索',
      iconUrl: 'http://120.46.171.159:9000/biscuit-tag-page/public/baidu-icon.svg',
      isDefault: true,
      fastKey: 'Alt + 1'
    }, {
      id: 2,
      name: '谷歌搜索',
      iconUrl: 'http://120.46.171.159:9000/biscuit-tag-page/public/google-icon.svg',
      isDefault: true,
      fastKey: 'Alt + 2'
    }, {
      id: 3,
      name: '火狐搜索',
      iconUrl: 'http://120.46.171.159:9000/biscuit-tag-page/public/firefox-icon.svg',
      isDefault: true,
      fastKey: 'Alt + 3'
    }, {
      id: 4,
      name: '必应搜索',
      iconUrl: 'http://120.46.171.159:9000/biscuit-tag-page/public/bing-icon.svg',
      isDefault: true,
      fastKey: 'Alt + 4'
    }
  ]);

  // 点击搜索组件事件
  let clickSearch = () => {
    if (styleStore.search.top) {
      styleStore.search.method.cancelSourceListDisplay(); // 关闭可能打开的搜索源列表
      return;
    }
    store.search.keyword = '';
    inputFocus.value.focus();
    styleStore.search.method.displayTop(); // 置顶显示
  }

  // 点击搜索源列表中的某一项时
  let updateSearchEngine = (data) => {
    styleStore.search.method.cancelSourceListDisplay(); // 搜索源列表隐藏
    store.search.defaultSearchEngine = Object.assign({}, data);
  }

  let toSearch = (keyword, url) => {
    if (store.search.defaultSearchEngine.name !== '百度搜索') {
      ElMessage.error('其它搜索引擎暂未开通，请切换百度搜索引擎！')
      return;
    }

    // 判断地址是否为空
    if (url === null) {
      url = 'https://www.baidu.com/s?wd=' + keyword;
    } else {
      store.search.keyword = keyword;
    }

    // 搜索源列表隐藏
    styleStore.search.method.cancelSourceListDisplay();

    // 联想词列表高度置为0
    styleStore.search.suggestHeight = 0;

    // 判断日志id是否存在，存在则需要请求服务器更新日志
    if (store.search.logId !== 0) {
      // 向服务器异步发起请求
      searchApi.updateLog(store.search.logId, keyword);
      // 重置日志id
      store.search.logId = 0;
    }

    // 转向其他页面
    window.open(url, "_blank");
  }


  let timeoutVar = null;
  let getKeywordSuggest = () => {
    // 搜索源列表隐藏
    styleStore.search.method.cancelSourceListDisplay();

    // 计时器防抖节流
    if (timeoutVar) {
      clearTimeout(timeoutVar);
    }

    // 关键字为空判断
    if (store.search.keyword === '') {
      styleStore.search.suggestHeight = 0;  // 联想词列表高度置为0
      return;
    }

    // 向服务器请求联想词列表
    timeoutVar = setTimeout(() => {
      // 校验所选搜索引擎
      if (store.search.defaultSearchEngine.name !== '百度搜索') {
        ElMessage.error('其它搜索引擎暂未开通，请切换百度搜索引擎！')
        return;
      }
      // 开始请求服务器
      let request = {
        type: store.search.defaultSearchEngine.id,
        keyword: store.search.keyword
      }
      searchApi.suggest(request).then(response => {

        // 判断用户是否已经退出搜索
        if (!styleStore.search.top) return;

        // 开始处理请求结果
        ResponseUtil.data(response).dispose(response => {
          // 获取到本次搜索的日志id
          store.search.logId = response.data.logId;

          if (response.code === '200' && response.data.list.length > 0) {
            styleStore.search.method.cancelSourceListDisplay();
            suggestList.value = response.data.list;
            styleStore.search.suggestHeight = response.data.list.length * 32;
          } else {
            styleStore.search.suggestHeight = 0;  // 联想词列表高度置为0
          }

        })

      })
    }, 1000);
  }

  const hover = () => {
    if (temp) {
      clearTimeout(temp);
      initLoadVar.value = false;
    }
    styleStore.search.method.changeHover()
  }

</script>
<template>

  <!-- 搜索框最外层盒子 -->
  <div @mouseleave.stop="styleStore.search.method.changeHover()" @mouseenter.stop="hover"
       @click="clickSearch"
       :class="['search-basic',
              styleStore.search.hover ? 'search-basic-hover':'search-basic-not-hover',
              initLoadVar ? 'search-init-slide-animation':'',
              styleStore.search.status === 1 ? 'search-show-animation':'',
              styleStore.search.status === 2 ? 'search-hide-animation':'']"
  >

    <!-- 搜索框搜索引擎图标 -->
    <div @click.stop="styleStore.search.method.displaySourceList()"
         :class="['search-logo-basic',
            styleStore.search.focus ? 'search-logo-and-btn-icon-focus':'search-logo-and-btn-icon-not-focus']"
    >
      <img :class="['search-logo-img']"
           :src="store.search.defaultSearchEngine.iconUrl" :alt="store.search.defaultSearchEngine.name" :title="store.search.defaultSearchEngine.name">
    </div>

    <!-- 搜索框搜索输入框 -->
    <div :class="['search-text-basic']"
        >
      <input type="text" v-model="store.search.keyword" ref="inputFocus" @input="getKeywordSuggest()"
       :class="['search-text-input', styleStore.search.hover ? 'search-text-input-hover':'search-text-input-not-hover']"
      >
    </div>

    <!-- 搜索框搜索按钮图标 -->
    <div @click.stop="toSearch(store.search.keyword, null)"
         :class="['search-btn-basic', styleStore.search.focus ? 'search-logo-and-btn-icon-focus':'search-logo-and-btn-icon-not-focus']">
      <el-icon>
        <Search />
      </el-icon>
    </div>




    <!-- 搜索框搜索引擎列表 -->
    <div @click.stop=""
         :class="['search-engine-list-basic', styleStore.search.source ? 'search-engine-list-open':'search-engine-list-close']">
      <div class="search-engine-item" v-for="(item, index) in searchEngineList" :key="item.id"
        @click="updateSearchEngine(item)">
        <div class="search-engine-item-logo">
          <img class="search-engine-item-logo-img" :src="item.iconUrl" :alt="item.name">
        </div>
        <div class="search-engine-item-text">{{ item.name }}</div>
        <div class="search-engine-item-fastKey">{{ item.fastKey }}</div>
      </div>
    </div>

    <!-- 关键词搜索关联词列表最外层盒子 -->
    <div :class="['search-suggest-basic']" :style="'height:' + styleStore.search.suggestHeight + 'px'">
      <!-- 关键词搜索关联词列表项 -->
      <div class="search-suggest-item" v-for="(item, index) in suggestList" :key="index" @click.stop="toSearch(item.text, item.redirectUrl)">
        {{ item.text }}
      </div>
    </div>

  </div>
</template>
<style scoped>

  /* 搜索框最外层盒子基本样式 */
  .search-basic {
    height: 46px;
    box-shadow: 0 0 10px 5px rgba(56, 56, 56, .6);
    position: absolute;
    top: 158px;
    border-radius: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all .3s;
    cursor: pointer;
    padding: 0 6px 0 6px;
  }


  /* 搜索框搜索引擎logo基础样式 */
  .search-logo-basic {
    width: 42px;
    height: 42px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all .2s;
    border-radius: 25px;
  }
  /* 搜索框搜索引擎图标图片样式 */
  .search-logo-img {
    width: 45%;
    height: auto;
  }


  /* 搜索框输入框基础样式 */
  .search-text-basic {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
  }
  /* 搜输入框input基本样式 */
  .search-text-input {
    width: 100%;
    height: auto;
    padding: 0;
    margin: 0;
    color: rgb(49, 49, 49);
    font-size: 16px;
    outline: none;
    border: none;
    text-align: center;
    background-color: transparent;
    cursor: pointer;
  }


  /* 搜索框搜索按钮基础样式 */
  .search-btn-basic {
    width: 42px;
    height: 42px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 22px;
    transition: all .2s;
    border-radius: 25px;
  }

  /* 搜索框搜索引擎列表基础样式 */
  .search-engine-list-basic {
    width: 240px;
    overflow: hidden;
    background-color: white;
    position: absolute;
    top: 56px;
    left: 0;
    border-radius: 15px;
    padding: 4px;
    cursor: default;
  }
  /* 搜索框搜索引擎item样式 */
  .search-engine-item {
    margin: 0 auto;
    width: 100%;
    height: 40px;
    border-radius: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all .2s;
  }
  .search-engine-item:hover {
    background-color: rgba(0, 0, 0, .1);
  }
  /* 搜索框搜索引擎item图片样式 */
  .search-engine-item-logo {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .search-engine-item-logo-img {
    width: 40%;
    height: auto;
  }
  /* 搜索框搜索引擎item文字样式 */
  .search-engine-item-text {
    width: 150px;
    height: 40px;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: rgb(56, 56, 56);
  }
  /* 搜索框搜索引擎item快捷键样式 */
  .search-engine-item-fastKey {
    width: 60px;
    height: 40px;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: rgb(94, 94, 94);
  }

  /* 搜索框搜索关联词列表最外层盒子基础样式 */
  .search-suggest-basic {
    overflow: hidden;
    width: 540px;
    position: absolute;
    top: 56px;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(50px) saturate(2.25);
    box-shadow: 0 0 10px 5px rgba(56, 56, 56, .2);
    transition: height .4s;
  }
  .search-suggest-item {
    width: 100%;
    height: 32px;
    text-indent: 16px;
    font-size: 15px;
    display: flex;
    align-items: center;
    color: rgb(58, 58, 58);
    transition: text-indent .1s, background-color .1s;
  }
  .search-suggest-item:hover {
    background-color: rgba(255, 255, 255, .6);
    text-indent: 21px;
  }




  /* 搜索框最外层盒子悬浮与不悬浮动态样式 */
  .search-basic-hover {
    width: 540px;
    left: calc(50% - 276px);
    background-color: rgba(255, 255, 255, .6);
  }
  .search-basic-not-hover {
    width: 280px;
    left: calc(50% - 146px);
    background-color: rgba(208, 208, 208, .1);
  }


  /* 搜索框搜索输入框文字悬浮与不悬浮动态样式 */
  .search-text-input-hover {
    color: rgb(38, 38, 38);
  }
  .search-text-input-not-hover {
    color: rgb(50, 50, 50);
  }


  /* 搜索框搜索引擎 & 搜索框搜索按钮图标 - 搜索输入框有焦点与无焦点动态样式 */
  .search-logo-and-btn-icon-focus {
    opacity: 1;
  }
  .search-logo-and-btn-icon-not-focus {
    opacity: 0;
  }


  /* 搜索框搜索源列表打开与关闭动态样式 */
  .search-engine-list-open {
    animation-name: searchSourceOpenAnimation;
    animation-duration: 0.5s;
    display: block;
  }
  .search-engine-list-close {
    animation-name: searchSourceCloseAnimation;
    animation-duration: 0.5s;
    display: none;
  }



  .search-show-animation {
    animation-name: showAnimation;
    animation-duration: 0.4s;
    animation-fill-mode: forwards;
  }
  .search-hide-animation {
    display: none;
    animation-name: hideAnimation;
    animation-duration: 0.4s;
    animation-fill-mode: forwards;
  }

  /* 搜索框初始化滑动显示效果 */
  .search-init-slide-animation {
    animation-name: initSlideAnimation;
    animation-duration: 0.7s;
    animation-fill-mode: forwards;
  }

  @keyframes showAnimation {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
  @keyframes hideAnimation {
    from {
      display: flex;
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }

  @keyframes initSlideAnimation {
    from {
      width: 0;
      left: calc(50%);
    }
    to {
      width: 280px;
      left: calc(50% - 146px);
    }
  }


  @keyframes searchSourceOpenAnimation {
    0% {
      opacity: 0;
      transform: scale(0.3);
    }
    50% {
      display: block;
      opacity: 0.5;
      transform: scale(1.05);
    }
    100%{
      display: block;
      opacity: 1;
      transform: scale(1);
    }
  }

  @keyframes searchSourceCloseAnimation {
    0% {
      display: block;
      opacity: 1;
      transform:translateX(0px) translateX(0px) scale(1);
    }
    100%{
      opacity: 0;
      transform:translateX(-70px) translateY(-70px) scale(0.3);
      display: none;
    }
  }

</style>